<template>
  <div class="selector-wrap disf dirc h">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="关键字"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-select
            v-model="queryParams.warehouseId"
            placeholder="全部"
            style="width: 120px"
            clearable
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id || ''"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="全部" style="width: 120px" clearable>
            <el-option
              v-for="item in typeEnum"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="flex1 h0">
      <el-table height="100%" :data="filteredDatas" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" v-if="!operation" />
        <el-table-column label="仓库名称" prop="warehouseName" width="150" />
        <el-table-column label="材料名称" prop="name" width="150" />
        <el-table-column label="材料类型" width="150">
          <template #default="scope">
            {{ Inventory_LABEL[scope.row.type] }}
          </template>
        </el-table-column>
        <el-table-column label="材料编码" prop="sku" width="150" />
        <el-table-column label="规格" align="center" min-width="150" prop="spec" />
        <el-table-column label="数量" align="center" min-width="80" prop="quantity">
          <template #default="scope">
            <span :style="{ color: scope.row.quantity < 10 ? 'red' : 'green' }">
              {{ scope.row.quantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="锁定数" align="center" min-width="80" prop="quantity">
          <template #default="scope">
            <span style="color: red">{{ scope.row.lockQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="市场价" align="center" min-width="80" prop="price" />
        <el-table-column label="成本价" align="center" min-width="80" prop="costPrice" />
        <el-table-column label="单位" align="center" min-width="80" prop="unit" />
        <el-table-column fixed="right" align="center" label="操作" v-if="operation">
          <template #default="scope">
            <el-button
              v-if="operation == 'add'"
              type="primary"
              size="small"
              icon="plus"
              @click="handleAdd(scope.row)"
            >
              添加
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination
      v-if="total > 0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      style="height: 50px"
      @pagination="handleQuery"
    />
  </div>
</template>

<script setup lang="ts">
import { defineProps, defineEmits } from "vue";
import InventoryAPI, {
  InventoryPageQuery,
  InventoryPageVO,
  Inventory_LABEL,
} from "@/api/business/warehouse/inventory.api";
import WarehouseAPI, { WarehousePageVO } from "@/api/business/warehouse/warehouse.api";
import { cloneDeep } from "lodash-es";

const props = defineProps({
  warehouseId: {
    type: String,
    required: false,
  },
  modelValue: {
    type: Array,
    default: () => [],
  },
  // 操作类型 默认 无-勾选 add-添加数量
  operation: {
    type: String,
    default: "",
  },
  // 材料类型 可逗号拼接
  type: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["update:modelValue", "selection-change", "add-item"]);

const warehouseList = reactive<WarehousePageVO[]>([]); // 备选-仓库列表
const total = ref(0);
const filteredDatas = ref<InventoryPageVO[]>();
const checked = ref<InventoryPageVO[]>([]);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  warehouseId: props.warehouseId,
}) as InventoryPageQuery;

// 备选-类型（取决于props.type，默认全部 Inventory_LABEL）
const typeEnum = computed(() => {
  const inventorys = props.type ? props.type.split(",") : Object.keys(Inventory_LABEL);
  return inventorys.map((item): OptionType => {
    return {
      value: item,
      label: Inventory_LABEL[item],
    };
  });
});

onMounted(() => {
  loadWarehouses();
});
const loadWarehouses = () => {
  WarehouseAPI.loadAll().then((data) => {
    if (data.length > 0) {
      warehouseList.push(...data);
    }
  });
};

// 勾选
const handleSelectionChange = (selection: InventoryPageVO[]) => {
  checked.value = selection;
  emit("update:modelValue", selection);
  emit("selection-change", selection);
};

// 添加按钮
const handleAdd = (row: InventoryPageVO) => {
  ElMessage.success("添加成功");
  emit("add-item", row);
};

// 获取已选列表
function getChecked(): InventoryPageVO[] {
  return checked.value || [];
}

const handleQuery = () => {
  const qParams = cloneDeep(queryParams);
  qParams.type ||= props.type;
  InventoryAPI.getPage(qParams).then((data) => {
    filteredDatas.value = data.list;
    total.value = data.total;
  });
};

const handleResetQuery = () => {
  queryParams.keywords = "";
  queryParams.pageNum = 1;
  delete queryParams.warehouseId;
  delete queryParams.type;
  handleQuery();
};

defineExpose({
  getChecked,
  handleQuery,
});
</script>

<style scoped>
.selector-wrap {
  padding: 10px;
}
</style>
